$(function() {

    chapter.init();
})

var chapter = (function() {
    var list_thumb = new Array();

    function multiLinkHandler(data) {
        $('#parseLink_errMsg').show().find('.alert').html('Uploading Images...').attr('class', 'alert noMargin');
        $.post('/manga/ajax_get_image_multi_link', {
            data: data,
            mangaId: $('#manga_id').val(),
            chapterId: $('#chapter_id').val(),
            slug: $('#manga_slug').val()
        }, function(resp) {
            if (resp.err == 0) {
                resp.listImg.sort(function(a, b) {
                    return a.image_path > b.image_path;
                });
                for (var i = 0, item; i < resp.listImg.length; i++) {
                    item = resp.listImg[i];
                    createImageUploaded(item.image_path, item.furl);
                }
                $('#parseLinkInpt').val('');
                $('#parseLink_errMsg').show().find('.alert').html('Parsing Finish.').attr('class', 'alert alert-success noMargin');
            } else
                $('#parseLink_errMsg').show().find('.alert').html(resp.msg).attr('class', 'alert alert-error noMargin');

        }, 'json');
    }

    function singleLinkHandler() {
        $('#singleLinkBtn').click(function() {
            var val = $('#singleLinkInpt').val(),
                exp = '(?:([^:/?#]+):)?(?://([^/?#]*))?([^?#]*\.(?:gif|jpg|jpeg|png|bmp|GIF|JPEG|JPG|PNG|BMP|Gif|Jpg|Jpeg|Png|Bmp)$)',
                regex = new RegExp(exp);
            $('#singleLink_errMsg').hide();
            if (!regex.test(val)) {
                $('#singleLink_errMsg').show().find('.alert').html('Link invalid').attr('class', 'alert alert-error noMargin');
                return false;
            }
            $.post('/manga/ajax_get_image_single_link', {
                url: val,
                mangaId: $('#manga_id').val(),
                chapterId: $('#chapter_id').val(),
                slug: $('#manga_slug').val()
            }, function(resp) {
                var err;
                if (resp.err == 0) {
                    err = 'success';
                    createImageUploaded(resp.listImg.image_path, resp.listImg.furl);
                    $('#singleLinkInpt').val('');
                } else
                    err = 'error';
                $('#singleLink_errMsg').show().find('.alert').html(resp.msg).attr('class', 'alert alert-' + err + ' noMargin');
            }, 'json');
            return false;
        });
    }

    function uploadNewHandler() {
        $('#chapter_uploader').pluploadQueue({
            runtimes: 'html5',
            url: '/manga/ajax_upload_chapter_image',
            max_file_size: '5mb',
            multipart_params: {
                mangaId: $('#manga_id').val(),
                chapterId: $('#chapter_id').val(),
                slug: $('#manga_slug').val()
            },
            chunk_size: '1mb',
            unique_names: true,
            sortable: true,
            filters: [{title: "Image files", extensions: "jpg,gif,png"}],
            init: {
                FileUploaded: function(up, file, info) {
                    var resp = JSON.parse(info.response);
                    resp.err == 0 && list_thumb.push({path: resp.image_path, furl: resp.furl});
                },
                UploadComplete: function(up, files) {
                    up.splice();
                    up.refresh();
                    $(".plupload_buttons").css("display", "inline");
                    $(".plupload_upload_status").css("display", "inline");
                    $(".plupload_start").addClass("plupload_disabled");

                    list_thumb.sort(function(a, b) {
                        return a.path > b.path;
                    });
                    $.each(list_thumb, function(i, item) {
                        var path = item.path,
                            furl = item.furl;
                        createImageUploaded(path, furl);
                    });
                    list_thumb = [];
                },
                BeforeUpload: function(uploader, file) {
                },
                Error: function(up, args) {

                }
            }
        });
    }

    function createImageUploaded(path, furl) {
        var html = '<li class="newPic">\
                        <input class="picval" type="hidden" value="' + path + '" />\
                        <a href="#">\
                            <img alt="" src="' + furl + '">\
                        </a>\
                        <div align="center" class="actions">\
                            <div class="actionsContainer">\
                                    <a class="ctrlButton removeImage" href="#" onclick="return chapter.removeImage(this);"><img alt="" src="/assets/img/icons/14x14/trash.png"></a>\
                                    <a href="' + furl + '" rel="group" class="ctrlButton fancybox"><img alt="" src="/assets/img/icons/14x14/magnifier.png"></a>\
                            </div>\
                        </div>\
                    </li>';
        $('#listImg ul').append(html);
    }

    function imagaListHandler() {
        $('#parseLinkBtn').click(function() {
            var val = $('#parseLinkInpt').val(),
                chapterId = $('#chapter_id').val(),
                from = $('#parseLinkOpt').val(),
                exp = '((http|https):\/\/(\w+:{0,1}\w*@)?(\S+)|)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?',
                regex = new RegExp(exp);
            $('#parseLink_errMsg').hide();
            if (!regex.test(val)) {
                $('#parseLink_errMsg').show().find('.alert').html('Link invalid').attr('class', 'alert alert-error noMargin');
                return false;
            }
            $('#parseIframe').html('');
            $('#parseLink_errMsg').show().find('.alert').html('Getting HTML...').attr('class', 'alert noMargin');
            chapter.parseChapterHandler(val, chapterId, from, '', function(resp) {
                if (resp.err == 0) {
                    var html = '<iframe class="hide" src="' + resp.ifurl + '" width="0" height="0"></iframe>'
                    $('#parseIframe').append(html);
                    $('#parseLink_errMsg').show().find('.alert').html('Get HTML Finish. Start to parse image...').attr('class', 'alert noMargin');
                } else {
                    $('#parseLink_errMsg').show().find('.alert').html(resp.msg).attr('class', 'alert alert-error noMargin');
                }
            });
            return false;
        });

        $('#updateChapterCtn').click(function() {
            var picval = $('#listImg .chapterPic .picval'),
                listImg = new Array(),
                mangaId = $('#manga_id').val(),
                chapterId = $('#chapter_id').val();
            $('#chapterErr').attr('class', 'hide pull-right').hide().html('');
            $.each(picval, function(i, item) {
                listImg.push($(item).val());
            });
            chapter.addChapterImage(mangaId, chapterId, listImg, function(resp) {
                if (resp.err == 0) {
                    $('#chapterErr').addClass('text-success').show().html('Update Successful');
                    $('.thumbs.chapterPic li').removeClass('newPic');
                }
            });
            return false;
        });

        $('#emptyChapterCtn').click(function() {
            showConfirm({
                title: 'Empty Chapter',
                msg: 'Are you sure want to empty this chapter?',
                onYes: function() {
                    $('#listImg ul').html('');
                    $.post('/manga/ajax_remove_all_chapter', {
                        mangaId: $('#manga_id').val(),
                        chapterId: $('#chapter_id').val(),
                        slug: $('#manga_slug').val()
                    }, function(resp) {
                        if (resp.err != 0) {
                            $('#chapterErr').addClass('text-error').show().html('Remove chapter content false');
                        }
                    }, 'json');
                }
            });
            return false;
        });

        $('#deleteChapterCtn').click(function() {
            showConfirm({
                title: 'Delete Chapter',
                msg: 'Are you sure want to delete this chapter?',
                onYes: function() {
                    $('#listImg ul').html('');
                    $.post('/manga/ajax_delete_chapter', {
                        mangaId: $('#manga_id').val(),
                        chapterId: $('#chapter_id').val(),
                        slug: $('#manga_slug').val()
                    }, function(resp) {
                        if (resp.err != 0) {
                            $('#chapterErr').addClass('text-error').show().html('Remove chapter content false');
                        } else {
                            $('#chapterList li a[rel="' + $('#chapter_id').val() + '"]').remove();
                            $('#chapterDetail').hide();
                        }
                    }, 'json');
                }
            });
            return false;
        });
    }

    function chapter_handler() {
        $('#inpAddChapter').keypress(function(evt) {
            evt.keyCode == 13 && $('#btnAddChapter').click();
        });

        $('#btnAddChapter').click(function() {
            var mangaId = $('#manga_id').val(),
                num = $('#inpAddChapter').val();
            chapter.createNewChapter(mangaId, num);
            return false;
        });

        $('#chapterList li a').live('click', function() {
            var a = $(this),
                chapter = $(this).attr('rel');

            $('#chapterList li a').removeClass('selected').find('.badge').removeClass('bOlive');
            a.addClass('selected').find('.badge').addClass('bOlive');

            $.ajax({
                type: "POST",
                url: '/manga/ajax_get_chapter_image',
                data: {chapterId: chapter, mangaId: $('#manga_id').val()},
                dataType: 'json',
                beforeSend: function() {
                    $('#chapterBlock .widget').hide();
                    $('#chapterDetail').show();
                    $('#chapterDetail .nav-tabs li').removeClass('active');
                    $('#chapterDetail .nav-tabs li:first-child').addClass('active');
                    $('#chapterDetail .tab-pane').removeClass('active');
                    $('#chapterDetail .tab-pane:first-child').addClass('active');
                    $('#chapterDetail ul.chapterPic').html('');
                    $('#chapterErr').attr('class', 'hide pull-right').hide().html('');
                    $('#chapter_id').val(chapter);
                    $('#updateChapterCtn').attr('rel', chapter);
                },
                success: function(resp) {
                    if (resp.err != 0) {
                        $('#chapterErr').addClass('text-error').show().html(resp.msg);
                        return false;
                    }
                    if (!resp.data.images)
                        return false;
                    $.each(resp.data.images, function(i, img) {
                        var html = '<li>\
                                        <input class="picval" type="hidden" value="' + img + '" />\
                                        <a href="#">\
                                            <img alt="" src="/' + img + '">\
                                        </a>\
                                    </li>';
                        $('#chapterDetail ul.chapterPic').append(html);
                    });
                    return false;
                }
            });
            return false;
        });

        $('#showParseManga a').live('click', function() {
            $('#chapterBlock .widget').hide();
            $('#parseManga').show();
            return false;
        });
    }

    return {
        init: function() {
            chapter_handler();
            imagaListHandler();
            uploadNewHandler();
            singleLinkHandler();
        },
        removeImage: function(obj) {
            $(obj).parents('li').remove();
            return false;
        },
        truyentranhtuanMessage: function(data) {
            data = JSON.parse(data);
            for (var i = 0; i < data.length; i++)
                data[i] = 'http://truyentranhtuan.com' + data[i];
            $('#parseIframe').html('');
            multiLinkHandler(data);
        },
        parseChapterHandler: function(url, chapterId, from, fn, callback) {
            $.post('/manga/ajax_get_chapter_link_content', {
                url: url,
                chapterId: chapterId,
                from: from ? from : 0,
                cb: fn ? fn : ''
            }, function(resp) {
                $.isFunction(callback) && callback(resp);
            }, 'json');
        },
        createNewChapter: function(mangaId, chapterId, callback) {
            if (!/^[0-9]{1,4}$/i.test(chapterId)) {
                $('#inpAddChapter').addClass('error');
                return;
            }
            var url = '/manga/ajax_add_new_chapter';
            $.ajax({
                type: "POST",
                url: url,
                data: {chapterId: chapterId, mangaId: mangaId},
                dataType: 'json',
                beforeSend: function() {
                    $('#inpAddChapter').removeClass('error');
                },
                success: function(resp) {
                    if (resp.err == 0 && !$('#chapterList li a[rel="' + chapterId + '"]').length) {
                        var html = '<li class="alert-info" style="display:none;">\
                                        <a rel="' + chapterId + '" href="#">\
                                            <span class="badge noShadow bSky">' + chapterId + '</span>\
                                        </a>\
                                    </li>';
                        html = $(html);
                        $('#inpAddChapter').val('');
                        $('#chapterList').append(html);
                        html.fadeIn(500);
                        setTimeout(function() {
                            html.removeClass('alert-info');
                        }, 5000);
                    }
                    $.isFunction(callback) && callback(resp);
                }
            });
        },
        addChapterImage: function(mangaId, chapterId, listImg, callback) {
            $.post('/manga/ajax_add_chapter_image', {
                mangaId: mangaId,
                chapterId: chapterId,
                images: listImg
            }, function(resp) {
                $.isFunction(callback) && callback(resp);
            }, 'json');
        }

    };

})();

